package com.suoluo.zenadmin.service.dest;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.suoluo.zenadmin.common.CommonResp;
import com.suoluo.zenadmin.common.PageUtil;
import com.suoluo.zenadmin.common.StringUtil;
import com.suoluo.zenadmin.common.SystemType;
import com.suoluo.zenadmin.common.UBB;
import com.suoluo.zenadmin.common.config.SystemConfigHolder;
import com.suoluo.zenadmin.common.file.FileEntry;
import com.suoluo.zenadmin.common.file.UploadImageManager;
import com.suoluo.zenadmin.dao.dest.DestDAO;
import com.suoluo.zenadmin.dao.dest.DestFeatureCategoryDAO;
import com.suoluo.zenadmin.oss.OSSService;
import com.suoluo.zenadmin.service.ImageException;
import com.suoluo.zenadmin.service.InfoService;
import com.suoluo.zenadmin.service.ServiceException;
import com.suoluo.zenadmin.vo.BaseInfoVO;
import com.suoluo.zenadmin.vo.ImageVO;
import com.suoluo.zenadmin.vo.PageVO;
import com.suoluo.zenadmin.vo.country.ContinentVO;
import com.suoluo.zenadmin.vo.country.CountryVO;
import com.suoluo.zenadmin.vo.dest.DestActivityVO;
import com.suoluo.zenadmin.vo.dest.DestAllFeatureVO;
import com.suoluo.zenadmin.vo.dest.DestFeature2VO;
import com.suoluo.zenadmin.vo.dest.DestFeatureCategoryVO;
import com.suoluo.zenadmin.vo.dest.DestFeatureItem2VO;
import com.suoluo.zenadmin.vo.dest.DestPathVO;
import com.suoluo.zenadmin.vo.dest.DestVO;
import com.suoluo.zenadmin.vo.dest.SelectFeatureItemVO;
import com.suoluo.zenadmin.vo.hotel.Hotel2VO;

public class DestServiceImpl implements DestService {

	@Autowired
	private DestDAO destDAO;
	
	@Autowired
	private DestFeatureCategoryDAO categoryDAO;

	@Resource(name = "ossService")
	private OSSService ossService;
	@Resource(name = "infoService")
	private InfoService infoService;

	

	
	@Override
	public List<DestVO> findSimplestDests(String destName, PageVO page) {
		int rows = page.getRows();
		int start = PageUtil.calcStartRow(page.getPage(), rows);
		if (StringUtils.hasLength(destName)) {
			destName = "%" + destName + "%";
		} else {
			destName = null;
		}
		return destDAO.findSimplestDests(destName, start, rows);
	}

	@Override
	public int findDestCount(String destName) {
		if (StringUtils.hasLength(destName)) {
			destName = "%" + destName + "%";
		} else {
			destName = null;
		}
		return destDAO.findDestCount(destName);
	}

	@Override
	public List<CountryVO> findCountries() {
		return destDAO.findCountries();
	}

	@Override
	public void saveDest(DestVO destVO) {
		try {
			// 保存目的地信息,获取目的地Id
			int destId = destDAO.saveDest(destVO);
			destVO.setDataId(destId);
			destVO.setInfoType(SystemType.INFO_DEST);
			destVO.setDefaultInfo(SystemType.BIT_TRUE);
			// 保存目的地基础信息，获取infoId
			infoService.saveBaseInfo(destVO);
			destVO.setInfoId(destVO.getInfoId());
			// 保存目的地图片
			infoService.saveImage(destVO);
			// 更新imageId
			destDAO.updateDestImageId(destVO.getDataId(), destVO.getImageId());

		} catch (ImageException e) {
			throw e;
		} catch (Exception e) {
			ossService.deleteImage(destVO.getSource());
			throw new ServiceException(CommonResp.FAIL_CODE, "目的地保存失败！", e);
		}
	}

	@Override
	public DestVO findDestById(int destId) {
		DestVO dest = destDAO.findDestById(destId, SystemType.INFO_DEST);
		if (dest == null){
			return null;
		}
		dest.setName(StringUtil.buildCompleteName(dest.getZhname(),
				dest.getEnname()));
		return dest;
	}

	@Override
	public void updateDest(DestVO destVO) {
		MultipartFile mfile = destVO.getImagepart();
		String imageName = null;
		try {
			// 修改目的地信息
			destDAO.updateDest(destVO);
			// 修改基础信息
			infoService.updateBaseInfo(destVO);
			// 如果图片已修改，则修改图片信息
			if (mfile != null && !mfile.isEmpty()) {
				// 更新图片
				infoService.updateImage(destVO);
			}
		} catch (ImageException e) {
			throw e;
		} catch (Exception e) {
			ossService.deleteImage(imageName);
			throw new ServiceException(CommonResp.FAIL_CODE, "目的地信息修改失败！", e);
		}
	}

	@Override
	public void deleteDest(DestVO destVO) {
		int destId = destVO.getDestId();
		// 判断是否可以删除
		int res = destDAO.findDestForginKeyCount(destId);
		if (res > 0) {
			throw new ServiceException(CommonResp.FAIL_CODE,
					"目的地下已关联其他业务，不可以删除！");
		}
		destVO.setDataId(destId);
		destVO.setInfoType(SystemType.INFO_DEST);
		// 删除目的地
		destDAO.deleteDest(destId);
		// 删除图片
		infoService.deleteBaseInfo(destVO);

	}

	@Override
	public List<DestActivityVO> findListDestActivity(int destId) {
		return destDAO.findDestActivity(destId);
	}

	@Override
	public void saveDestActivity(DestActivityVO activity) {
		FileEntry entry = null;
		try {
			entry = UploadImageManager.saveDestActivityImg(activity.getMfile(),
					activity.getDestId());
			if (entry == null) {
				throw new ServiceException(CommonResp.FAIL_CODE, "目的地活动图片保存失败！");
			}
			activity.setActivityImg(entry.getFilePath());
			destDAO.saveDestActivity(activity);
		} catch (Exception e) {
			if (e instanceof ServiceException) {
				throw (ServiceException) e;
			}
			UploadImageManager.deleteFile(entry);
			throw new ServiceException(CommonResp.FAIL_CODE, "目的地活动保存失败！");
		}

	}

	@Override
	public DestActivityVO findDestActivityById(int activityId) {
		return destDAO.findDestActivityById(activityId);
	}

	@Override
	public void updateDestActivity(DestActivityVO activity) {
		FileEntry entry = null;
		try {
			// 判断图片是否更新
			MultipartFile mfile = activity.getMfile();
			FileEntry oldEntry = new FileEntry(activity.getActivityImg());
			entry = UploadImageManager.replaceFile(mfile, oldEntry);
			if (entry != null) {
				activity.setActivityImg(entry.getFilePath());
			}
			// 更新数据
			destDAO.updateActivity(activity);
		} catch (Exception e) {
			UploadImageManager.deleteFile(entry);
			throw new ServiceException(CommonResp.FAIL_CODE,
					"目的地即将到来的活动信息保存失败！");
		}

	}

	@Override
	public void deleteDestActivity(DestActivityVO activity) {
		// 删除图片
		FileEntry entry = new FileEntry(activity.getActivityImg());
		UploadImageManager.deleteFile(entry);
		// 删除数据
		destDAO.deleteDestActivity(activity.getActivityId());
	}

	@Override
	public List<DestFeature2VO> findSimpleDestFeatures(int destId) {
		return destDAO.findSimpleDestFeatures(destId);
	}

	@Override
	public void deleteDestFeature(DestFeature2VO feature) {
		int featureId = feature.getFeatureId();
		int res = destDAO.findFeatureForeignKeyCount(featureId);
		if (res > 0) {
			throw new ServiceException(CommonResp.FAIL_CODE, "该特色已关联特色项，不可以删除！");
		}
		feature.setDataId(featureId);
		feature.setInfoType(SystemType.INFO_DEST_FEATURE);
		// 删除特色信息
		destDAO.deleteDestFeature(featureId);
		// 删除基础信息
		infoService.deleteBaseInfo(feature);

	}

	// @Override
	// public List<DestFeatureCategoryPOJO> findNoAddFeatureCategory(int destId,
	// int categoryId) {
	// List<DestFeatureCategoryPOJO> data = destDAO.findNoAddFeatureCategory(
	// destId, categoryId);
	// data = changeCategoryDesc(data);
	// return data;
	// }



	@Override
	public List<DestFeatureItem2VO> findFeatureItemWithoutContent(int featureId) {
		return destDAO.findSimplestFeatureItems(featureId);
	}



	@Override
	public DestFeatureItem2VO findFeatureItemById(int featureItemId) {
		DestFeatureItem2VO item = destDAO.findFeatureItemById(featureItemId,
				SystemType.INFO_DEST_FEATURE_ITEM);
		if (item != null) {
			item.setName(StringUtil.buildCompleteName(item.getZhname(),
					item.getEnname()));
		}

		return item;
	}

	@Override
	public DestFeatureItem2VO findSimplestFeatureItemById(int featureItemId) {
		DestFeatureItem2VO featureItem = destDAO.findSimplestFeatureItemById(featureItemId);
		if (featureItem == null){
			return null;
		}
		featureItem.setName(StringUtil.buildCompleteName(featureItem.getZhname(), featureItem.getEnname()));
		return featureItem;
	}

	
	@Override
	public void saveHotelFeatureItem(DestFeatureItem2VO item) {
		int featureId = item.getFeatureId();
		int[] hotelInfo = item.getHotelIds();
		if (hotelInfo == null || hotelInfo.length == 0) {
			throw new ServiceException(CommonResp.FAIL_CODE,
					"添加失败，没有选择酒店信息,请勾选酒店信息！");
		}
		int destId = item.getDestId();
		// 根据目的地Id获取目的地下未勾选的酒店信息
		List<Hotel2VO> list = destDAO.findListDestHotel(destId, featureId);
		List<DestFeatureItem2VO> hotelList = new ArrayList<DestFeatureItem2VO>();
		for (Integer hotelId : hotelInfo) {
			DestFeatureItem2VO itemPOJO = new DestFeatureItem2VO();

			for (Hotel2VO hotel : list) {
				if (hotelId == hotel.getHotelId()) {
					itemPOJO.setUrl(hotel.getUrl());
					itemPOJO.setName(hotel.getZhname());
					itemPOJO.setDestId(hotel.getDestId());
					itemPOJO.setLat(hotel.getLat());
					itemPOJO.setLng(hotel.getLng());
					itemPOJO.setRelId(hotelId);
					itemPOJO.setFeatureId(featureId);
					itemPOJO.setZhname(hotel.getZhname());
					itemPOJO.setEnname(hotel.getEnname());
					itemPOJO.setCreateTime(new Date());
					itemPOJO.setSummary(hotel.getSummary());
					itemPOJO.setAddress(hotel.getAddress());
					itemPOJO.setEmail(hotel.getEmail());
					itemPOJO.setImageId(hotel.getImageId());
					itemPOJO.setLogo(hotel.getLogo());
					itemPOJO.setMobileImageId(hotel.getMobileImageId());
					itemPOJO.setPrice(hotel.getPrice());
					itemPOJO.setPropertyVisible(SystemType.BIT_TRUE);
					itemPOJO.setTel(hotel.getTel());
					itemPOJO.setFeatureCategoryId(SystemConfigHolder
							.getDestFeatureCategoryForHotel());
					hotelList.add(itemPOJO);
				}
			}

		}
		destDAO.saveHotelFeatureItem(hotelList);
	}

	@Override
	public void deleteFeatureItem(DestFeatureItem2VO item, int featureCategoryId) {
		int itemId = item.getFeatureItemId();
		// 判断是不是酒店，酒店不用删除图片
		int hotelType = SystemConfigHolder.getDestFeatureCategoryForHotel();
		if (hotelType != featureCategoryId) {
			DestFeatureItem2VO itemVO = destDAO.findFeatureItemById(itemId,
					SystemType.INFO_DEST_FEATURE_ITEM);
			// 删除特色项图片信息
			infoService.deleteBaseInfo(itemVO);
			// 删除logo
			ossService.deleteImage(item.getLogo());
		}
		// 防止特色项被选中为推荐选项，先删除，推荐表中可能存在的记录
		destDAO.deleteSelectItemByItemId(itemId);
		// 删除特色项
		destDAO.deleteDestFeatureItem(itemId);

	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<Map> findListFeatureSelectItem(int featureId) {
		return destDAO.findListFeatureSelectItem(featureId);
	}

	@Override
	public void saveSelectFeatureItem(SelectFeatureItemVO itemVO) {

		String checkInfo = itemVO.getCheckInfo();
		int selectItemId = itemVO.getSelectItemId();
		if (checkInfo == null && selectItemId != 0) {
			destDAO.deleteSelectFeatureItem(selectItemId);
			return;
		}
		// 判断该特色选择了几条推荐的特色项了
		int count = destDAO.findSelectFeatureItemCount(itemVO.getFeatureId());
		// 等于3条不能添加
		if (count >= 3) {
			throw new ServiceException(CommonResp.FAIL_CODE,
					"推荐的特色项不能大于3条，请先删除再添加！");
		} else {
			destDAO.saveSelectFeatureItem(itemVO);
		}

	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<Map> findListAllFeatureItem(int featureId) {
		return destDAO.findListAllFeatureItem(featureId);
	}

	@Override
	public List<Hotel2VO> findListDestHotel(int destId, int featureId) {
		return destDAO.findListDestHotel(destId, featureId);
	}

	/**
	 * 查询目的地导航的搜索树导航
	 * 
	 * @return
	 */
	@Override
	public List<ContinentVO> findDestNavigateTree() {
		@SuppressWarnings("rawtypes")
		List<Map> result = destDAO.findDestNavigateTree();
		return findNavigateTree(result);
	}

	@SuppressWarnings("rawtypes")
	private List<ContinentVO> findNavigateTree(List<Map> result) {
		Map<Object, ContinentVO> continentMap = new HashMap<Object, ContinentVO>();
		Map<Object, CountryVO> countryMap = new HashMap<Object, CountryVO>();
		for (Map<Object, Object> entry : result) {
			// 洲编号
			Object continentID = entry.get("t_continent_id");
			ContinentVO continent = continentMap.get(continentID);
			if (continent == null) {
				continent = new ContinentVO();
				continent.setContinentId((Integer) continentID);
				continent.setContinentName((String) entry
						.get("t_continent_name"));
				continentMap.put(continentID, continent);
			}

			// 国家信息
			Object countryId = entry.get("t_country_id");
			if (countryId == null) {
				continue;
			}
			CountryVO country = countryMap.get(countryId);
			if (country == null) {
				country = new CountryVO();
				country.setCountryId((Integer) countryId);
				country.setCountryName((String) entry.get("t_country_name"));
				continent.addCountry(country);
				countryMap.put(countryId, country);
			}

			// 目的地信息
			Object destId = entry.get("dest_id");
			if (destId == null) {
				continue;
			}
			DestVO dest = new DestVO();
			dest.setDestId((Integer) destId);
			dest.setZhname((String) entry.get("zhname"));
			dest.setEnname((String) entry.get("enname"));
			dest.setName(StringUtil.buildCompleteName(dest.getZhname(),
					dest.getEnname()));
			dest.setLat((BigDecimal) entry.get("lat"));
			dest.setLng((BigDecimal) entry.get("lng"));
			dest.setSource((String) entry.get("source"));
			dest.setSmall((String) entry.get("small"));
			// dest.setDestLat((Double) entry.get("t_dest_lat"));
			// dest.setDestLng((Double) entry.get("t_dest_lng"));
			// dest.setDestOrigImg((String) entry.get("t_dest_orig_img"));
			// dest.setDestMiniImg((String) entry.get("t_dest_mini_img"));
			// 添加到国家信息
			country.addDest(dest);
		}

		List<ContinentVO> continents = new ArrayList<ContinentVO>(
				continentMap.values());
		if (SystemConfigHolder.isEnableTempCountrySort()) {
			if (continents.size() >= 1) {
				// 默认第一个是亚洲
				ContinentVO asia = continents.get(0);
				List<CountryVO> tempcountries = new ArrayList<CountryVO>();
				CountryVO[] sortCountry = new CountryVO[6];
				for (CountryVO country : asia.getCountrys()) {
					String name = country.getCountryName();
					if (name.contains("中国")){
						sortCountry[0] = country;
					} else if (name.contains("马尔代夫共和国")) {
						sortCountry[1] = country;
					} else if (name.contains("印度尼西亚")) {
						sortCountry[2] = country;
					} else if (name.contains("泰国")) {
						sortCountry[3] = country;
					} else if (name.contains("柬埔寨")) {
						sortCountry[4] = country;
					} else if (name.contains("越南")) {
						sortCountry[5] = country;
					} else {
						tempcountries.add(country);
					}
				}

				for (int i = sortCountry.length - 1; i >= 0; i--) {
					if (sortCountry[i] == null) {
						continue;
					}
					tempcountries.add(0, sortCountry[i]);
				}
				asia.setCountrys(tempcountries);
			}
			if (continents.size() >= 2) {
				// 默认第一个是欧洲
				ContinentVO europe = continents.get(1);
				List<CountryVO> tempcountries = new ArrayList<CountryVO>();
				CountryVO[] sortCountry = new CountryVO[7];
				for (CountryVO country : europe.getCountrys()) {
					String name = country.getCountryName();
					if (name.contains("法国")) {
						sortCountry[0] = country;
					} else if (name.contains("奥地利")) {
						sortCountry[1] = country;

					} else if (name.contains("摩纳哥")) {
						sortCountry[2] = country;

					} else if (name.contains("意大利")) {
						sortCountry[3] = country;
					} else if (name.contains("捷克")) {
						sortCountry[4] = country;
					} else if (name.contains("丹麦")) {
						sortCountry[5] = country;
					} else if (name.contains("英国")) {
						sortCountry[6] = country;
					} else {
						tempcountries.add(country);
					}
				}
				for (int i = sortCountry.length - 1; i >= 0; i--) {
					if (sortCountry[i] == null) {
						continue;
					}
					tempcountries.add(0, sortCountry[i]);
				}
				europe.setCountrys(tempcountries);
			}
			// 非洲和大洋洲互换位置，并将毛里求斯共和放到非洲的第一个位置
			if (continents.size() >= 4) {
				Collections.swap(continents, 2, 3);
				// 默认第一个是欧洲
				ContinentVO europe = continents.get(2);
				List<CountryVO> tempcountries = new ArrayList<CountryVO>();
				CountryVO coun = null;
				for (CountryVO country : europe.getCountrys()) {
					String name = country.getCountryName();
					if (name.contains("毛里求斯共和国")) {
						coun = country;
					} else {
						tempcountries.add(country);
					}
				}
				tempcountries.add(0, coun);
				europe.setCountrys(tempcountries);
			}
		}
		return continents;
	}

	@Override
	public DestPathVO findDestPath(int destId) {
		DestPathVO path = destDAO.findDestPath(destId);
		path.setDestName(StringUtil.buildCompleteName(path.getZhname(),
				path.getEnname()));
		return path;

	}

	@Override
	public List<DestFeatureItem2VO> findSamilarDestFeatureItems(int itemId,
			int featureId, int pageSize) {
		List<DestFeatureItem2VO> items = destDAO.findSamilarDestFeatureItems(
				itemId, featureId, pageSize);
		for (DestFeatureItem2VO item : items) {
			item.setName(StringUtil.buildCompleteName(item.getZhname(),
					item.getEnname()));
		}
		return items;
	}



	@Override
	public DestAllFeatureVO findDestAllFeatures(int destId) {
		// 查询目的地下所有特色
		List<DestFeature2VO> features = destDAO
				.findDestFeaturesWithoutContentByDestId(destId);
		// 查询目的地每个特色默认选择的特色项
		List<DestFeatureItem2VO> items = destDAO
				.findSelectedSimplestDestFeatureItemsByDestId(destId);

		List<DestFeature2VO> otherFeatures = new ArrayList<DestFeature2VO>();
		DestFeature2VO specialFeatures = null;
		Map<Integer, DestFeature2VO> featuresIndex = new HashMap<Integer, DestFeature2VO>();
		StringBuilder keyword = new StringBuilder();
		for (DestFeature2VO f : features) {
			if (f.getFeatureCategoryId() == SystemConfigHolder
					.getDestFeatureCategorySpecial()) {
				specialFeatures = f;
			} else {
				otherFeatures.add(f);
			}
			featuresIndex.put(f.getFeatureId(), f);
			keyword.append(f.getZhname() + ",");
		}
		for (DestFeatureItem2VO item : items) {
			DestFeature2VO f = featuresIndex.get(item.getFeatureId());
			if (f == null) {
				continue;
			}
			f.addDestFeatureItem(item);
			item.setName(StringUtil.buildCompleteName(item.getZhname(),
					item.getEnname()));
		}
		//查询特别体验下的所有特色项
		if (specialFeatures != null){
			List<DestFeatureItem2VO> sepecialItems = destDAO.findSimplestFeatureItems(specialFeatures.getFeatureId());
			for (DestFeatureItem2VO item : sepecialItems){
				item.setName(StringUtil.buildCompleteName(item.getZhname(), item.getEnname()));
			}
			specialFeatures.setDestFeatureItems(sepecialItems);
		}
		DestAllFeatureVO vo = new DestAllFeatureVO();
		vo.setOtherFeatures(otherFeatures);
		vo.setSpecialExperience(specialFeatures);
		vo.setKeyword(keyword.toString());
		return vo;

	}

	@Override
	public List<DestFeatureItem2VO> findFeatureItemsWithoutContentByFeatureId(
			int featureId) {
		List<DestFeatureItem2VO> items = destDAO
				.findFeatureItemsWithoutContentByFeatureId(featureId);
		for (DestFeatureItem2VO item : items) {
			item.setName(StringUtil.buildCompleteName(item.getZhname(),
					item.getEnname()));
		}
		return items;
	}



	@Override
	public List<DestVO> findDestsWithoutContent() {
		List<DestVO> dests = destDAO.findDestsWithoutContent();
		for (DestVO dest : dests) {
			dest.setName(StringUtil.buildCompleteName(dest.getZhname(),
					dest.getEnname()));
		}
		return dests;
	}

//	@Override
//	public List<TripFeatureVO> findListFeatureByDestId(int destId) {
//		return destDAO.findListFeatureByDestId(destId);
//	}


	@Override
	public List<ContinentVO> findHotelNavigateTree() {
		@SuppressWarnings("rawtypes")
		List<Map> result = destDAO.findHotelNavigateTree();
		return findNavigateTree(result);
	}


	@Override
	public DestFeature2VO findDestFeatureById(int featureId) {
		return destDAO.findDestFeatureById(featureId,
				SystemType.INFO_DEST_FEATURE);
	}

	@Override
	public DestVO findSimplestDestById(int destId) {
		DestVO dest = destDAO.findSimplestDestById(destId);
		dest.setName(StringUtil.buildCompleteName(dest.getZhname(),
				dest.getEnname()));
		return dest;
	}

	@Override
	public DestFeature2VO findSimplestDestFeatureById(int featureId) {
		return destDAO.findSimplestFeatureById(featureId);
	}

	@Override
	public DestVO findDestWithoutContentById(int destId) {
		DestVO dest = destDAO.findDestWithoutContentById(destId);
		dest.setName(StringUtil.buildCompleteName(dest.getZhname(),
				dest.getEnname()));
		return dest;
	}

	@Override
	public List<BaseInfoVO> findSubItemsForFeatureItem(int featureItemId) {
		List<BaseInfoVO> subItems = infoService.findBaseInfos(featureItemId, SystemType.INFO_DEST_FEATURE_ITEM);
		Map<Integer,BaseInfoVO> subItemMap = new HashMap<Integer, BaseInfoVO>();
		int [] infoIds = new int[subItems.size()];
		int i = 0;
		for (BaseInfoVO sub : subItems){
			subItemMap.put(sub.getInfoId(), sub);
			infoIds[i++] = sub.getInfoId();
		}
		List<ImageVO> images = infoService.findImages(infoIds);
		for (ImageVO img : images){
			BaseInfoVO info = subItemMap.get(img.getInfoId());
			info.addImage(img);
		}
		return subItems;
	}

	@Override
	public void saveFeatureItemText(BaseInfoVO infoVO) {
		List<String> list = null;
		try {
			// 设置数据类型
			infoVO.setInfoType(SystemType.INFO_DEST_FEATURE_ITEM);
			// 设置是否是默认属性
			infoVO.setDefaultInfo(SystemType.BIT_FALSE);
			// 保存描述信息
			infoService.saveBaseInfo(infoVO);
			list = ossService.putImages(infoVO.getImageFiles());
			// 保存图片
			infoService.saveImage(infoVO.getInfoId(), list);
		} catch (Exception e) {
			ossService.deleteImages(list);
			throw new ServiceException(CommonResp.FAIL_CODE, "保存特色项的图文信息失败！", e);
		}

	}

	@Override
	public BaseInfoVO findBaseInfoById(int infoId) {
		return infoService.findBaseInfoById(infoId);
	}

	@Override
	public void updateFeatureItemText(BaseInfoVO base) {
		infoService.updateBaseInfo(base);
	}

	@Override
	public void deleteFeatureItemText(BaseInfoVO base) {
		infoService.deleteBaseInfoById(base.getInfoId());
	}

	@Override
	public List<ImageVO> findListFeatureItemImages(int infoId) {
		return infoService.findImages(infoId);
	}

	@Override
	public void saveFeatureItemImage(BaseInfoVO infoVO) {
		List<String> imageKeys = null;
		try {
			imageKeys = ossService.putImages(infoVO.getImageFiles());
			infoService.saveImage(infoVO.getInfoId(), imageKeys);
		} catch (Exception e) {
			ossService.deleteImages(imageKeys);
			throw new ServiceException(CommonResp.FAIL_CODE, "特色项多图保存失败！", e);
		}

	}

	@Override
	public List<DestFeatureItem2VO> findListAloneFeatureItem(PageVO page) {
		int pageRows = page.getRows();
		int curPage = page.getPage();
		int start = PageUtil.calcStartRow(curPage, pageRows);
		return destDAO.findListAloneFeatureItem(start,pageRows);
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public DestFeatureItem2VO findCompleteFeatureItemById(int featureItemId) {
		DestFeatureItem2VO featureItem = this.findSimplestFeatureItemById(featureItemId);
		if (featureItem == null){
			return null;
		}
		List<BaseInfoVO> subItems = this.findSubItemsForFeatureItem(featureItemId);
		Iterator<BaseInfoVO> ite = subItems.iterator();
		
		//是否是特别体验
		boolean experience = (featureItem.getFeatureCategoryId() == SystemConfigHolder.getDestFeatureCategorySpecial());
		while (ite.hasNext()){
			BaseInfoVO sub = ite.next();
			sub.setContent(UBB.decode(sub.getContent()));
			if (!experience){
				if (sub.getDefaultInfo() == SystemType.BIT_TRUE){
					featureItem.setContent(sub.getContent());
					int imgnum = 0;
					for (ImageVO img : sub.getImages()){
						if (img.getImageId() == featureItem.getImageId()){
							featureItem.setSource(img.getSource());
							featureItem.setNormal(img.getNormal());
							featureItem.setMiddle(img.getMiddle());
							featureItem.setSmall(img.getSmall());
						} else {
							if (imgnum == 0){
								featureItem.setImage1(img);
								imgnum++;
							} else {
								featureItem.setImage2(img);
							}
						}
					}
					ite.remove();
				}
			}
		}
		featureItem.setSubItems(subItems);
		return featureItem;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<DestFeatureItem2VO> findFeatureItemsWithoutContent(int destId,
			int categoryId) {
		List<DestFeatureItem2VO> items = destDAO.findFeatureItemsWithoutContent(destId, categoryId);
		for (DestFeatureItem2VO item : items){
			item.setName(StringUtil.buildCompleteName(item.getZhname(), item.getEnname()));
		}
		return items;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<DestFeatureCategoryVO> findDestFeatureCatetories(int destId) {
		return destDAO.findDestFeatureCatetories(destId);
	}
	

	@Override
	public int findAloneFeatureItemCount() {
		return destDAO.findAloneFeatureItemCount();
	}
	@Override
	public void saveDestFeature(DestFeature2VO feature) {
		// 判断添加的特色类别是否已经添加，如果添加了过来提示不能重复添加
		int categoryId = feature.getFeatureCategoryId();
		int destId = feature.getDestId();
		int res = destDAO.findDestFeatureIsAdd(destId, categoryId);
		if (res > 0) {
			throw new ServiceException(CommonResp.FAIL_CODE,
					"已添加过此类别的特色，不可以重复添加！");
		}
		try {

			// 获取类别名称和顺序
			DestFeatureCategoryVO cate = categoryDAO.findDestFeatureCategoryById(categoryId);
			feature.setFeatureOrder(cate.getFeatureCategoryOrder());
			feature.setZhname(cate.getFeatureCategoryName());
			// 保存特色信息
			int featureId = destDAO.saveDestFeature(feature);
			feature.setFeatureId(featureId);
			feature.setDataId(featureId);
			// 设置信息类型
			feature.setInfoType(SystemType.INFO_DEST_FEATURE);
			feature.setDefaultInfo(SystemType.BIT_TRUE);
			// 保存基础信息
			infoService.saveBaseInfo(feature);
			// 保存图片信息
			infoService.saveImage(feature);
			// 更新图片Id
			destDAO.updateFeatureImageId(feature.getFeatureId(),
					feature.getImageId());
		} catch (ImageException e) {
			throw e;
		} catch (Exception e) {
			ossService.deleteImage(feature.getSource());
			throw new ServiceException(CommonResp.FAIL_CODE, "目的地特色保存失败!", e);
		}
	}

	@Override
	public void updateDestFeature(DestFeature2VO feature) {
		MultipartFile mfile = feature.getImagepart();
		int featureId = feature.getFeatureId();
		int categoryId = feature.getOldCategoryId();
		int newCategoryId = feature.getFeatureCategoryId();
		// 1.验证特色的类别是否发生改变
		if (newCategoryId != categoryId) {
			// 判断添加的特色类别是否已经添加，如果添加了过来提示不能重复添加
			int destId = feature.getDestId();
			int res = destDAO.findDestFeatureIsAdd(destId, newCategoryId);
			if (res > 0) {
				throw new ServiceException(CommonResp.FAIL_CODE,
						"已添加过此类别的特色，不可以重复添加！");
			}
			// 查询判断特色下的特色项是否已被勾选到首页，如果勾选了请先取消首页勾选，再做修改
			Integer homeCount = destDAO.findDestFeatureInHomeCategoryCount(
					featureId, categoryId);
			if (homeCount != null && homeCount > 0) {
				throw new ServiceException(CommonResp.FAIL_CODE,
						"该特色下的特色项已被勾选到首页，请先取消首页勾选，再做修改！");
			}
			// 如果类别被修改了，则修改归属类别信息
			DestFeatureCategoryVO cate = categoryDAO.findDestFeatureCategoryById(newCategoryId);
			feature.setFeatureCategoryId(cate.getFeatureCategoryId());
			feature.setFeatureOrder(cate.getFeatureCategoryOrder());
			feature.setZhname(cate.getFeatureCategoryName());
		}
		try {

			// 更新特色信息
			destDAO.updateDestFeature(feature);
			//更新特色项的类别Id
			destDAO.updateDestFeatureItemCategoryId(feature);
			if (mfile != null && !mfile.isEmpty()) {

				infoService.updateImage(feature);

			}
			// 更新基础信息
			infoService.updateBaseInfo(feature);

		} catch (ImageException e) {
			throw e;
		} catch (Exception e) {
			if (mfile != null && !mfile.isEmpty()) {
				ossService.deleteImage(feature.getSource());
			}
			throw new ServiceException(CommonResp.FAIL_CODE, "目的地特色更新失败！", e);
		}
	}
	@Override
	public void saveDestFeatureItem(DestFeatureItem2VO itemVO) {

		try {
			// 保存特色项logo
			MultipartFile mfile = itemVO.getLogoFile();
			if(mfile == null || mfile.isEmpty()){
				itemVO.setLogo(null);
			}
			else
			{
				String imageName = ossService.putImage(mfile);
				itemVO.setLogo(imageName);
			}
			
			// 判断是否添加了停留时间，如果没有添加就拿类别的停留时间
			int pauseTime = itemVO.getStayTime();
			if (pauseTime == 0) {
				pauseTime = categoryDAO.findCategoryDefaultPauseTime(itemVO
						.getFeatureCategoryId());
				itemVO.setStayTime(pauseTime);
			}
			itemVO.setCreateTime(new Date());
			// 保存特色项信息，获取Id
			int itemId = destDAO.saveDestFeatureItem(itemVO);
			itemVO.setFeatureItemId(itemId);
			// 设置数据类型，数据引用Id，是否是默认信息
			itemVO.setInfoType(SystemType.INFO_DEST_FEATURE_ITEM);
			itemVO.setDataId(itemId);
			itemVO.setDefaultInfo(SystemType.BIT_TRUE);
			// 保存基础信息，获取infoId
			infoService.saveBaseInfo(itemVO);
			// 保存图片信息,获取imageId
			infoService.saveImage(itemVO);
			// 更新图片Id到特色项表
			destDAO.updateDestFeatureItemImageId(itemVO.getFeatureItemId(),
					itemVO.getImageId());

		} catch (ImageException e) {
			throw e;
		} catch (Exception e) {
			ossService.deleteImage(itemVO.getSource());
			throw new ServiceException(CommonResp.FAIL_CODE, "特色项保存失败！", e);
		}
	}
	@Override
	public void updateDestFeatureItem(DestFeatureItem2VO itemVO) {
		MultipartFile logo = itemVO.getLogoFile();
		MultipartFile imageFile = itemVO.getImagepart();
		try {

			//判断特色类别是否改变，如果改变，需要更新特色项的特色Id
			int oldFeatureId= itemVO.getOldFeatureId();
			if(oldFeatureId != itemVO.getFeatureId()) {
				DestFeature2VO feature = destDAO.findSimplestFeatureById(itemVO.getFeatureId());;
				itemVO.setFeatureCategoryId(feature.getFeatureCategoryId());
			}
			// 判断是否添加了停留时间，如果没有添加就拿类别的停留时间
			int categoryId = itemVO.getFeatureCategoryId();
			int pauseTime = itemVO.getStayTime();
			if (pauseTime == 0) {
				pauseTime = categoryDAO.findCategoryDefaultPauseTime(categoryId);
				itemVO.setStayTime(pauseTime);
			}
			Date date = new Date();
			itemVO.setCreateTime(date);
			// 判断特色项logo是否修改
			if (logo != null && !logo.isEmpty()) {
				// 如果修改，修改logo
				String logoName = ossService
						.updateImage(logo, itemVO.getLogo());
				itemVO.setLogo(logoName);
			}
			// 更新特色项信息
			destDAO.updateDestFeatureItem(itemVO);
			// 更新基础信息
			infoService.updateBaseInfo(itemVO);
			// 判断特色项图片信是否修改
			if (imageFile != null && !imageFile.isEmpty()) {
				// 如果修改，修改特色项图片信息
				infoService.updateImage(itemVO);
			}

		} catch (ImageException e) {
			throw e;
		} catch (Exception e) {
			if (logo != null && !logo.isEmpty()) {
				ossService.deleteImage(itemVO.getLogo());
			}
			if (imageFile != null && !imageFile.isEmpty()) {
				ossService.deleteImage(itemVO.getLogo());
			}
			throw new ServiceException(CommonResp.FAIL_CODE, "特色项更新失败！");
		}
	}

	@Override
	public List<DestFeatureItem2VO> findListExpireFeatureItem(PageVO page) {
		int pageRows = page.getRows();
		int curPage = page.getPage();
		int start = PageUtil.calcStartRow(curPage, pageRows);
		Date date = new Date();
		return destDAO.findListExpireFeatureItem(date,start,pageRows);
	}

	@Override
	public int findExpireFeatureItemCount() {
		Date date = new Date();
		return destDAO.findExpireFeatureItemCount(date);
	}

	@Override
	public void deleteExpireFeatureItem(DestFeatureItem2VO item) {
		//更新失效特色项的删除状态
		destDAO.updateFeatureItemDeleted(item.getFeatureItemId());
		//删除推荐表中的数据
		destDAO.deleteSelectItemByItemId(item.getFeatureItemId());
	}

	@Override
	public List<DestFeatureItem2VO> find4FeatureItems(int destId) {
		List<DestFeatureItem2VO> items = destDAO.find4FeatureItems(destId);
		for (DestFeatureItem2VO item : items){
			item.setName(StringUtil.buildCompleteName(item.getZhname(), item.getEnname()));
		}
		return items;
	}

	@Override
	public List<DestVO> findAllDest() {
		return destDAO.findAllDest();
	}

	@Override
	public List<DestFeature2VO> findDestFeatures(int destId) {
		
		return destDAO.findDestFeatures(destId,SystemType.INFO_DEST_FEATURE);
	}

	@Override
	public List<DestFeatureItem2VO> findFeatureItems(List<Integer> featureIds) {
		return destDAO.findFeatureItems(featureIds);
	}


//	@Override
//	public void updateExpireFeatureItem(DestFeatureItem2VO item) {
//		//判断修改后的失效时间是否大于原来的失效时间，并且大于当前时间，
//		Timestamp oldExpireTime = item.getOldExpireTime();
//		Timestamp expireTime = item.getExpireTime();
//		try{
//			if(expireTime.after(oldExpireTime))
//			{
//				//创建时间改为当前时间
//				Date date = new Date();
//				item.setCreateTime(date);
//				//更新数据库
//				destDAO.updateExpireFeatureItem(item);
//			}
//			else
//			{
//				throw new ServiceException(CommonResp.FAIL_CODE,"更新失败，原因可能是实效时间未填写或者新的失效时间小于等于原有失效的时间");
//			}
//		}
//		catch (ServiceException e) {
//			throw e;
//		}
//		catch (Exception e) {
//			throw new ServiceException(CommonResp.FAIL_CODE,"失效特色项更新失败！",e);
//		}
//	}

}
